<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑文件夹' : '创建文件夹'"
    width="580px"
    :close-on-click-modal="false"
    @close="handleClose"
    class="knowledge-folder-create-dialog"
    align-center
  >
    <template #header>
      <div class="dialog-header">
        <div class="header-icon">
          <el-icon :size="24"><FolderOpened /></el-icon>
        </div>
        <div class="header-title">
          <h3>{{ isEdit ? '编辑文件夹' : '创建文件夹' }}</h3>
          <p class="header-subtitle">{{ isEdit ? '修改文件夹信息' : '创建新的文件夹来组织您的文档' }}</p>
        </div>
      </div>
    </template>

    <div class="dialog-body">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="110px"
        label-position="left"
        class="folder-form"
      >
        <div class="form-section">
          <div class="section-title">
            <el-icon><Document /></el-icon>
            <span>基本信息</span>
          </div>
          
          <el-form-item label="文件夹名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入文件夹名称"
              clearable
              maxlength="100"
              show-word-limit
              size="large"
              class="folder-name-input"
            >
              <template #prefix>
                <el-icon><Folder /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="父文件夹">
            <el-tree-select
              v-model="formData.parent_id"
              :data="folderTree"
              :props="{ label: 'name', value: 'id', children: 'children' }"
              placeholder="选择父文件夹（可选，留空则创建在根目录）"
              clearable
              check-strictly
              :render-after-expand="false"
              :disabled="isEdit && !!folder?.id"
              size="large"
              class="parent-folder-select"
            >
              <template #default="{ data }">
                <span>
                  <el-icon style="margin-right: 6px;"><Folder /></el-icon>
                  {{ data.name }}
                </span>
              </template>
            </el-tree-select>
            <div class="form-tip" v-if="isEdit && folder?.id">
              <el-icon><InfoFilled /></el-icon>
              编辑模式下不能修改父文件夹
            </div>
          </el-form-item>

          <el-form-item label="文件夹描述">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入文件夹描述（可选）"
              maxlength="500"
              show-word-limit
              resize="vertical"
              class="folder-description-input"
            />
          </el-form-item>
        </div>

        <div class="form-section">
          <div class="section-title">
            <el-icon><Lock /></el-icon>
            <span>权限设置</span>
          </div>

          <el-form-item label="访问权限">
            <div class="permission-group">
              <el-radio-group v-model="formData.permission" class="permission-radio-group">
                <el-radio-button label="public" class="permission-option">
                  <div class="permission-content">
                    <el-icon class="permission-icon public"><Unlock /></el-icon>
                    <div class="permission-info">
                      <div class="permission-name">公开</div>
                      <div class="permission-desc">所有人可见</div>
                    </div>
                  </div>
                </el-radio-button>
                <el-radio-button label="team" class="permission-option">
                  <div class="permission-content">
                    <el-icon class="permission-icon team"><User /></el-icon>
                    <div class="permission-info">
                      <div class="permission-name">团队</div>
                      <div class="permission-desc">团队成员可见</div>
                    </div>
                  </div>
                </el-radio-button>
                <el-radio-button label="private" class="permission-option">
                  <div class="permission-content">
                    <el-icon class="permission-icon private"><Lock /></el-icon>
                    <div class="permission-info">
                      <div class="permission-name">私有</div>
                      <div class="permission-desc">仅自己可见</div>
                    </div>
                  </div>
                </el-radio-button>
              </el-radio-group>
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button size="large" @click="handleClose">
          <el-icon><Close /></el-icon>
          取消
        </el-button>
        <el-button 
          type="primary" 
          size="large" 
          @click="handleSubmit" 
          :loading="saving"
          class="submit-button"
        >
          <el-icon v-if="!saving"><Check /></el-icon>
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage, type FormInstance } from 'element-plus'
import { 
  Folder, 
  FolderOpened, 
  Document, 
  Lock, 
  Unlock, 
  User, 
  InfoFilled,
  Check,
  Close
} from '@element-plus/icons-vue'
import { createKnowledgeFolder, updateKnowledgeFolder, getKnowledgeFolders, type KnowledgeFolder, type CreateKnowledgeFolderParams } from '@/api/knowledge'
import { ResponseParser } from '@/utils/responseParser'

interface Props {
  modelValue: boolean
  folder?: KnowledgeFolder | null
  defaultParentId?: string
  folderTree?: KnowledgeFolder[]
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'created', folder: KnowledgeFolder): void
  (e: 'updated', folder: KnowledgeFolder): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const isEdit = computed(() => !!props.folder)

const formRef = ref<FormInstance>()
const saving = ref(false)

const folderTree = ref<KnowledgeFolder[]>(props.folderTree || [])

const formData = reactive<{
  name: string
  parent_id?: string
  description?: string
  permission: 'public' | 'team' | 'private'
}>({
  name: '',
  parent_id: props.defaultParentId,
  description: '',
  permission: 'private'
})

const formRules = {
  name: [
    { required: true, message: '请输入文件夹名称', trigger: 'blur' },
    { min: 1, max: 100, message: '文件夹名称长度在 1 到 100 个字符', trigger: 'blur' }
  ]
}

// 加载文件夹树
const loadFolderTree = async () => {
  try {
    const response = await getKnowledgeFolders({ tree: true })
    const parsed = ResponseParser.parseResponse<KnowledgeFolder[]>(response)
    const allFolders = (parsed.success && parsed.data) ? parsed.data : []
    // 如果是编辑模式，过滤掉自己和子文件夹
    if (isEdit.value && props.folder?.id) {
      const filterFolders = (folders: KnowledgeFolder[]): KnowledgeFolder[] => {
        return folders.filter(f => f.id !== props.folder?.id).map(f => ({
          ...f,
          children: f.children ? filterFolders(f.children) : undefined
        }))
      }
      folderTree.value = filterFolders(allFolders)
    } else {
      folderTree.value = allFolders
    }
  } catch (error) {
    console.error('加载文件夹列表失败:', error)
  }
}

// 初始化表单数据
const initFormData = () => {
  if (isEdit.value && props.folder) {
    formData.name = props.folder.name
    formData.parent_id = props.folder.parent_id
    formData.description = props.folder.description || ''
    formData.permission = props.folder.permission || 'private'
  } else {
    formData.name = ''
    formData.parent_id = props.defaultParentId
    formData.description = ''
    formData.permission = 'private'
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    saving.value = true

    if (isEdit.value && props.folder) {
      // 更新文件夹
      const params: Partial<CreateKnowledgeFolderParams> = {
        name: formData.name,
        parent_id: formData.parent_id,
        description: formData.description,
        permission: formData.permission
      }
      const response = await updateKnowledgeFolder(props.folder.id, params)
      const parsed = ResponseParser.parseResponse<KnowledgeFolder>(response)
      if (parsed.success && parsed.data) {
        ElMessage.success('更新成功')
        emit('updated', parsed.data)
      } else {
        ElMessage.error(parsed.message || '更新失败')
      }
    } else {
      // 创建文件夹
      const params: CreateKnowledgeFolderParams = {
        name: formData.name,
        parent_id: formData.parent_id,
        description: formData.description,
        permission: formData.permission
      }
      const response = await createKnowledgeFolder(params)
      const parsed = ResponseParser.parseResponse<KnowledgeFolder>(response)
      if (parsed.success && parsed.data) {
        ElMessage.success('创建成功')
        emit('created', parsed.data)
      } else {
        ElMessage.error(parsed.message || '创建失败')
      }
    }
    handleClose()
  } catch (error: any) {
    if (error !== false) {
      console.error('操作失败:', error)
      ElMessage.error(error?.response?.data?.message || '操作失败')
    }
  } finally {
    saving.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  formRef.value?.resetFields()
  initFormData()
}

// 监听对话框打开
watch(visible, (val) => {
  if (val) {
    loadFolderTree()
    // 延迟初始化，确保 defaultParentId 已经更新
    nextTick(() => {
      initFormData()
    })
  }
})

// 监听 defaultParentId 变化（用于创建子文件夹时）
watch(() => props.defaultParentId, (newVal) => {
  if (visible.value && !isEdit.value) {
    formData.parent_id = newVal
  }
})

// 监听文件夹变化
watch(() => props.folder, () => {
  if (visible.value) {
    initFormData()
  }
}, { deep: true })
</script>

<style scoped lang="scss">
.knowledge-folder-create-dialog {
  :deep(.el-dialog__header) {
    padding: 0;
    border-bottom: none;
  }

  :deep(.el-dialog__body) {
    padding: 0;
  }

  :deep(.el-dialog__footer) {
    padding: 20px 24px;
    border-top: 1px solid #e2e8f0;
    background: linear-gradient(to bottom, #f8fafc 0%, #ffffff 100%);
  }

  .dialog-header {
    display: flex;
    align-items: flex-start;
    gap: 16px;
    padding: 24px 24px 20px;
    background: linear-gradient(135deg, #06b6d4 0%, #3b82f6 50%, #8b5cf6 100%);
    color: #fff;
    border-radius: 8px 8px 0 0;
    box-shadow: 0 4px 12px rgba(6, 182, 212, 0.15);

    .header-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 48px;
      height: 48px;
      background: rgba(255, 255, 255, 0.25);
      border-radius: 12px;
      flex-shrink: 0;
      backdrop-filter: blur(10px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .header-title {
      flex: 1;
      min-width: 0;

      h3 {
        margin: 0 0 4px 0;
        font-size: 20px;
        font-weight: 600;
        color: #fff;
      }

      .header-subtitle {
        margin: 0;
        font-size: 13px;
        color: rgba(255, 255, 255, 0.85);
        line-height: 1.5;
      }
    }
  }

  .dialog-body {
    padding: 24px;
    background: #fff;
  }

  .folder-form {
    .form-section {
      margin-bottom: 24px;

      &:last-child {
        margin-bottom: 0;
      }

      .section-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 16px;
        padding-bottom: 12px;
        border-bottom: 2px solid #e0f2fe;
        font-size: 15px;
        font-weight: 600;
        color: #0f172a;

        .el-icon {
          color: #06b6d4;
          font-size: 18px;
        }
      }
    }

    :deep(.el-form-item) {
      margin-bottom: 20px;

      .el-form-item__label {
        font-weight: 500;
        color: var(--el-text-color-primary);
        padding-bottom: 8px;
      }
    }

    .folder-name-input {
      :deep(.el-input__wrapper) {
        border-radius: 8px;
        box-shadow: 0 0 0 1px #e2e8f0 inset;
        transition: all 0.3s;

        &:hover {
          box-shadow: 0 0 0 1px #06b6d4 inset;
        }

        &.is-focus {
          box-shadow: 0 0 0 2px #06b6d4 inset;
        }
      }
    }

    .parent-folder-select {
      width: 100%;

      :deep(.el-select__wrapper) {
        border-radius: 8px;
        box-shadow: 0 0 0 1px #e2e8f0 inset;
        transition: all 0.3s;

        &:hover {
          box-shadow: 0 0 0 1px #06b6d4 inset;
        }

        &.is-focused {
          box-shadow: 0 0 0 2px #06b6d4 inset;
        }
      }
    }

    .folder-description-input {
      :deep(.el-textarea__inner) {
        border-radius: 8px;
        border: 1px solid #e2e8f0;
        transition: all 0.3s;

        &:hover {
          border-color: #06b6d4;
        }

        &:focus {
          border-color: #06b6d4;
          box-shadow: 0 0 0 2px rgba(6, 182, 212, 0.1);
        }
      }
    }

    .form-tip {
      display: flex;
      align-items: center;
      gap: 6px;
      margin-top: 8px;
      font-size: 12px;
      color: var(--el-text-color-secondary);
      line-height: 1.5;

      .el-icon {
        font-size: 14px;
        color: var(--el-color-warning);
      }
    }

    .permission-group {
      width: 100%;

      .permission-radio-group {
        display: flex;
        gap: 12px;
        width: 100%;

        .permission-option {
          flex: 1;
          height: auto;
          padding: 0;
          border-radius: 8px;
          overflow: hidden;
          transition: all 0.3s;

          :deep(.el-radio-button__inner) {
            width: 100%;
            padding: 16px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            background: #f8fafc;
            transition: all 0.3s;
            box-shadow: none;

            &:hover {
              border-color: #06b6d4;
              background: #ecfeff;
            }
          }

          :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
            border-color: #06b6d4;
            background: linear-gradient(135deg, #ecfeff 0%, #cffafe 100%);
            color: #0891b2;
            box-shadow: 0 0 0 3px rgba(6, 182, 212, 0.15);
          }

          .permission-content {
            display: flex;
            align-items: center;
            gap: 12px;

            .permission-icon {
              font-size: 24px;
              flex-shrink: 0;

              &.public {
                color: #10b981;
              }

              &.team {
                color: #3b82f6;
              }

              &.private {
                color: #f59e0b;
              }
            }

            .permission-info {
              flex: 1;
              min-width: 0;
              text-align: left;

              .permission-name {
                font-size: 14px;
                font-weight: 600;
                color: var(--el-text-color-primary);
                margin-bottom: 4px;
              }

              .permission-desc {
                font-size: 12px;
                color: var(--el-text-color-secondary);
                line-height: 1.4;
              }
            }
          }
        }
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;

    .submit-button {
      min-width: 100px;
      font-weight: 500;
      background: linear-gradient(135deg, #06b6d4 0%, #3b82f6 100%);
      border: none;
      transition: all 0.3s;

      &:hover {
        background: linear-gradient(135deg, #0891b2 0%, #2563eb 100%);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(6, 182, 212, 0.3);
      }

      &:active {
        transform: translateY(0);
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .knowledge-folder-create-dialog {
    :deep(.el-dialog) {
      width: 95% !important;
      margin: 5vh auto;
    }

    .dialog-header {
      flex-direction: column;
      text-align: center;

      .header-icon {
        margin: 0 auto;
      }
    }

    .folder-form {
      .permission-group {
        .permission-radio-group {
          flex-direction: column;

          .permission-option {
            width: 100%;
          }
        }
      }
    }
  }
}
</style>

